package com.d3works.apps.crm.web;

import com.d3works.apps.crm.db.Catalog;
import com.d3works.apps.crm.db.repo.CatalogRepository;
import com.d3works.apps.tool.file.PdfTool;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.meta.MetaFiles;
import com.d3works.meta.db.MetaFile;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import java.nio.file.Path;

public class CatalogController {

  public void showPdf(ActionRequest request, ActionResponse response) {

    try {
      Catalog catalog =
          Beans.get(CatalogRepository.class)
              .find(request.getContext().asType(Catalog.class).getId());
      MetaFile pdf = catalog.getPdfFile();
      String title = catalog.getName();
      Path path = MetaFiles.getPath(pdf.getFileName());
      String fileLink =
          PdfTool.getFileLinkFromPdfFile(
              PdfTool.printCopiesToFile(path.toFile(), 1), title + ".pdf");
      response.setView(ActionView.define(title).add("html", fileLink).map());

    } catch (Exception e) {
      TraceBackService.trace(e);
    }
  }
}
